<template>
    <div>
        <el-row :gutter="15" class="mb8">
            <el-col :span="1.5">
                <el-button icon="el-icon-plus" plain size="mini" @click="authorizedDevice"
                    v-hasPermi="['maintenance:device:add']">授权sim卡信息
                </el-button>
            </el-col>
            <el-form :model="queryParams" ref="queryParamsRef" label-width="70px" @submit.prevent inline
                class="el-form-search">
                <!--设备名称-->
                <!--sim卡ICCID-->
                <el-form-item label="电话号码" prop="phone" class="el-form-search-item">
                    <el-input clearable placeholder="输入电话号码" v-model.trim="queryParams.phone"></el-input>
                </el-form-item>
                <!-- 下拉框 -->
                <el-form-item class="el-form-search-item">
                    <el-button type="primary" size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button size="mini" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-table ref="deiveAuthorize" @row-click="handleRowClick" :data="deviceList" :height="tableHeight"

      v-loading="loading" border stripe @expand-change="handleExpandChange"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column align="center" label="#" type="index" width="50" :resizable="false">
                <template slot-scope="scope">
                    <span>{{
                        (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="ICCID" prop="iccId" :resizable="false" show-overflow-tooltip
                width="150"></el-table-column>
            <el-table-column align="center" label="电话" prop="phone" :resizable="false" show-overflow-tooltip
                width="150"></el-table-column>
            <el-table-column align="center" label="无线sn码" prop="sn" :resizable="false" show-overflow-tooltip
                width="120"></el-table-column>
            <el-table-column align="center" label="无线IMEI" prop="imei" :resizable="false"></el-table-column>
            <el-table-column align="center" label="合约套餐" prop="contractPackage" :resizable="false"></el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />


        <el-dialog title="授权" :visible.sync="authorizeOpen">
            <el-table :data="authorizedDeviceList" v-loading="loading" border>
                <el-table-column align="center" label="ICCID" prop="iccId" :resizable="false" show-overflow-tooltip
                    width="150"></el-table-column>
                <el-table-column align="center" label="无线sn码" prop="sn" :resizable="false" show-overflow-tooltip
                    width="120"></el-table-column>
                <el-table-column align="center" label="无线IMEI" prop="imei" :resizable="false"></el-table-column>
                <el-table-column align="center" label="合约套餐" prop="contractPackage"
                    :resizable="false"></el-table-column>
                <el-table-column align="center" label="是否授权" prop="authorizeStatus" width="80" :resizable="false">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.authorizeStatus === 1 ? 'success' : 'danger'">{{
                            scope.row.authorizeStatus === 1 ? '已授权' : '未授权'
                            }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="130">
                    <template slot-scope="scope">
                        <el-button type="text"
                            v-if="userInfo.userName !== scope.row.createBy && scope.row.authorizeStatus == 1"
                            @click="cancelAuthorize(scope.row)">取消授权</el-button>
                        <el-button type="text" @click="handleDeleteAuthorize(scope.row, scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAuthorizedForm">确认授权</el-button>
                <el-button @click="authorizeOpen = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { addDeviceAuthorized } from '@/api/authorization/deviceAuthorized'
import {
    getDeviceStatus,
} from "@/api/maintenance/dimensionTables";
import { listDeviceAuthorized, cancelAuthorized } from '@/api/authorization/deviceAuthorized'

import { listUser } from '@/api/system/user'
import { listSubstation, listSubstationFold } from "@/api/maintenance/substation";
import { listSimCard } from '@/api/maintenance/simCard'

export default {
    data() {
        return {
            authorizedDeviceList: [],
            deviceList: [],
            authorizeOpen: false,
            substationOptions: [],
            userList: [],
            devStatusOptions: [],
            total: 0,
            loading: false,
            tableHeight: 'calc(100vh - 350px)',// 遮罩层
            authorizeForm: {
                userId: ''
            }, //

            // 搜索框
            queryParams: {
                pageNum: 1,
                pageSize: 30,
                devStatus: '',
                substationNum: '',
                phone: '',
                devName: ""
                // orderByColumn: "update_time",
                // isAsc: "ASC",
            },
        }
    },
    props: {
        userInfo: {
            type: Object,
            default: () => ({})
        }
    },
    computed: {
        statusFormat() {
            return (status) => {
                const statusMap = ['success', 'danger', 'waring', 'info']
                return statusMap[status] || "";
            }

        }
    },
    created() {
        listSubstation().then((response) => {
            this.substationOptions = response.rows;
        }); // 设备状态列表
        getDeviceStatus().then((response) => {
            this.devStatusOptions = response.data;
        });

        listUser().then((response) => {
            this.userList = response.rows;
        })
        this.getList()
    },
    methods: {

        cancelAuthorize(row) {
            this.$confirm('是否取消当前授权?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                cancelAuthorized({
                    userId: this.userInfo.userId,
                    deviceId: row.num,
                    type: 3
                }).then(res => {
                    this.$message.success("取消授权成功")
                    row.authorizeStatus = "0"
                })
            }).catch(() => {

            });
        },
        handleUserChange() {
            this.loading = true
            listDeviceAuthorized({ userId: this.userInfo.userId, type: "3" }).then(res => {
                let authorizationList = res.rows
                this.authorizedDeviceList.forEach(e => {
                    let obj = authorizationList.find(f => f.deviceId === e.num)
                    this.$set(e, 'authorizeStatus', obj ? 1 : 0)
                    if (this.userInfo.userName == e.createBy) {
                        this.$set(e, 'authorizeStatus', 1)
                    }
                })
                this.loading = false
            })
        },
        handleDeleteAuthorize(row, i) {
            this.$refs.deiveAuthorize.toggleRowSelection(row, false)
            //    this.authorizedDeviceList.splice(i,1)
        },
        authorizedDevice() {
            if (!this.userInfo.userId) {
                this.$message.error("请先选择授权用户")
                return;
            }
            if (this.authorizedDeviceList.length === 0) {
                this.$message.error("请选择授权SIM信息")
                return;
            }
            this.authorizeOpen = true;
            this.authorizedDeviceList.forEach(e => {
                this.$set(e, 'authorizeStatus', 0)
            })
            this.handleUserChange()
        },
        handleSelectionChange(data) {
            console.log(data)
            this.authorizedDeviceList = data;
        },
        handleExpandChange(row) {
            this.chInfoSourceData = this.devInfoSourceData + row.devInfoSource + "\\";
        },
        handleRowClick(row) {
            this.$refs.deiveAuthorize.toggleRowSelection(row)
        },
        handleRefresh() {
            this.resetForm("queryParamsRef");
            this.getList();
        },
        //查询设备信息
        getList() {
            this.loading = true;
            listSimCard(this.queryParams).then((res) => {
                this.deviceList = res.rows;
                this.deviceOptions = res.rows; //设置下拉框数据；
                this.total = res.total;
          this.$refs.elTable.doLayout();
                this.loading = false;
            });
        },
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        submitAuthorizedForm() {
            if (!this.userInfo.userId) {
                this.$message.error("请选择授权用户")
                return;
            }
            if (this.authorizedDeviceList.length === 0) {
                this.$message.error("请选择设备")
                return;
            }
            // if (this.authorizedDeviceList.some(s => s.authorizeStatus == 1)) {
            //     this.$message.error("厂站信息已授权，请删除已授厂站信息后重新提交")
            //     return
            // }
            let resultList = this.authorizedDeviceList.filter(f => f.authorizeStatus != 1).map(m => {
                return {
                    userId: this.userInfo.userId,
                    deviceId: m.num,
                    type: "3"
                }
            })
            if (resultList.length === 0) {
                this.$message.error("请添加未授权SIM卡")
                return;
            }
            addDeviceAuthorized(resultList).then(response => {
                this.$message.success("授权成功")
                this.$refs.deiveAuthorize.clearSelection()
                this.authorizeOpen = false;
            })
        },
    }
}
</script>
<style lang="scss" scoped>
.autocomplete-item-disabled {
    color: #999;
    cursor: not-allowed;
    pointer-events: none;
    /* 禁止点击 */
}

/* 默认隐藏操作列 */
.operation-column {
    visibility: hidden;
}

/* 当鼠标悬停在行上时显示操作列 */
.el-table__row:hover .operation-column {
    visibility: visible;
}

/* 确保按钮在列显示时可见 */
.operation-buttons {
    white-space: nowrap;
}
</style>
